/*
 * Project: purple
 * 
 * File Created at 2018年12月7日
 * 
 */
package xin.mydreams.purple.handle;

import java.lang.reflect.Method;
import java.util.Map;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import xin.mydreams.purple.config.PurpleSetting;
import xin.mydreams.purple.constant.req.PurpleHttpRequest;
import xin.mydreams.purple.constant.resp.PurpleHttpResponse;

/**
 * 请求处理中心
 * 
 * @Type PurpleHttpDispatcherHandle.java
 * @email guzehao@mydreams.xin
 * @author 谷泽昊
 * @blog https://www.mydreams.xin
 * @date 2018年12月7日 下午9:10:04
 * @version
 */
@ChannelHandler.Sharable
public class PurpleHttpDispatcherHandle extends SimpleChannelInboundHandler<DefaultHttpRequest> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DefaultHttpRequest httpRequest) {
		try {
			//
			PurpleHttpRequest purpleHttpRequest = new PurpleHttpRequest(httpRequest);
			Map<String, Method> methodMapping = PurpleSetting.getMethodMapping();
			Map<String, Object> classMap = PurpleSetting.getClassMap();
			String path = purpleHttpRequest.getPath().replaceAll("/+", "/");
			HttpMethod httpMethod = purpleHttpRequest.getMethod();
			String name = httpMethod.name();
			Method method = methodMapping.get(path);
			Object controller = classMap.get(path);
			if (method != null && controller != null) {
				Object invoke = method.invoke(controller, purpleHttpRequest.getParamMap());
				PurpleHttpResponse.sendJson(ctx, String.valueOf(invoke));
			} else {
				PurpleHttpResponse.sendJson(ctx, String.valueOf("404"));
			}

		} catch (Exception e) {
			e.printStackTrace();
			PurpleHttpResponse.sendJson(ctx, e.getMessage());
		}

	}
}

/**
 *
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2018年12月7日 谷泽昊 creat
 */